$(function() {
	var singleIds = [];
	$.getJSON(getRootPath()+"user/getAllUserIdCombo.do",function(result){
		singleIds = result;
	});
	
    $('#mytimer').html('<canvas id="canvas"></canvas>');
    var timer;
    var ctrlStatus, recStatus;
    var WINDOW_WIDTH = $(window).width()-20;
    var WINDOW_HEIGHT = 300; 
    var OFFSET_X = 250;
    var OFFSET_Y = 30;
    var RADIUS = 7; //球半径
    var NUMBER_GAP = 10; //数字之间的间隙
    var u = 0.65; //碰撞能量损耗系数
    var context; //Canvas绘制上下文
    var balls = []; //存储彩色的小球
    const colors = ["#33B5E5", "#0099CC", "#AA66CC", "#9933CC", "#99CC00", "#669900", "#FFBB33", "#FF8800", "#FF4444", "#CC0000"]; //彩色小球的颜色
    var currentNums = []; //屏幕显示的8个字符
    var digit =
        [
            [
                [0,0,1,1,1,0,0],
                [0,1,1,0,1,1,0],
                [1,1,0,0,0,1,1],
                [1,1,0,0,0,1,1],
                [1,1,0,0,0,1,1],
                [1,1,0,0,0,1,1],
                [1,1,0,0,0,1,1],
                [1,1,0,0,0,1,1],
                [0,1,1,0,1,1,0],
                [0,0,1,1,1,0,0]
            ],//0
            [
                [0,0,0,1,1,0,0],
                [0,1,1,1,1,0,0],
                [0,0,0,1,1,0,0],
                [0,0,0,1,1,0,0],
                [0,0,0,1,1,0,0],
                [0,0,0,1,1,0,0],
                [0,0,0,1,1,0,0],
                [0,0,0,1,1,0,0],
                [0,0,0,1,1,0,0],
                [1,1,1,1,1,1,1]
            ],//1
            [
                [0,1,1,1,1,1,0],
                [1,1,0,0,0,1,1],
                [0,0,0,0,0,1,1],
                [0,0,0,0,1,1,0],
                [0,0,0,1,1,0,0],
                [0,0,1,1,0,0,0],
                [0,1,1,0,0,0,0],
                [1,1,0,0,0,0,0],
                [1,1,0,0,0,1,1],
                [1,1,1,1,1,1,1]
            ],//2
            [
                [1,1,1,1,1,1,1],
                [0,0,0,0,0,1,1],
                [0,0,0,0,1,1,0],
                [0,0,0,1,1,0,0],
                [0,0,1,1,1,0,0],
                [0,0,0,0,1,1,0],
                [0,0,0,0,0,1,1],
                [0,0,0,0,0,1,1],
                [1,1,0,0,0,1,1],
                [0,1,1,1,1,1,0]
            ],//3
            [
                [0,0,0,0,1,1,0],
                [0,0,0,1,1,1,0],
                [0,0,1,1,1,1,0],
                [0,1,1,0,1,1,0],
                [1,1,0,0,1,1,0],
                [1,1,1,1,1,1,1],
                [0,0,0,0,1,1,0],
                [0,0,0,0,1,1,0],
                [0,0,0,0,1,1,0],
                [0,0,0,1,1,1,1]
            ],//4
            [
                [1,1,1,1,1,1,1],
                [1,1,0,0,0,0,0],
                [1,1,0,0,0,0,0],
                [1,1,1,1,1,1,0],
                [0,0,0,0,0,1,1],
                [0,0,0,0,0,1,1],
                [0,0,0,0,0,1,1],
                [0,0,0,0,0,1,1],
                [1,1,0,0,0,1,1],
                [0,1,1,1,1,1,0]
            ],//5
            [
                [0,0,0,0,1,1,0],
                [0,0,1,1,0,0,0],
                [0,1,1,0,0,0,0],
                [1,1,0,0,0,0,0],
                [1,1,0,1,1,1,0],
                [1,1,0,0,0,1,1],
                [1,1,0,0,0,1,1],
                [1,1,0,0,0,1,1],
                [1,1,0,0,0,1,1],
                [0,1,1,1,1,1,0]
            ],//6
            [
                [1,1,1,1,1,1,1],
                [1,1,0,0,0,1,1],
                [0,0,0,0,1,1,0],
                [0,0,0,0,1,1,0],
                [0,0,0,1,1,0,0],
                [0,0,0,1,1,0,0],
                [0,0,1,1,0,0,0],
                [0,0,1,1,0,0,0],
                [0,0,1,1,0,0,0],
                [0,0,1,1,0,0,0]
            ],//7
            [
                [0,1,1,1,1,1,0],
                [1,1,0,0,0,1,1],
                [1,1,0,0,0,1,1],
                [1,1,0,0,0,1,1],
                [0,1,1,1,1,1,0],
                [1,1,0,0,0,1,1],
                [1,1,0,0,0,1,1],
                [1,1,0,0,0,1,1],
                [1,1,0,0,0,1,1],
                [0,1,1,1,1,1,0]
            ],//8
            [
                [0,1,1,1,1,1,0],
                [1,1,0,0,0,1,1],
                [1,1,0,0,0,1,1],
                [1,1,0,0,0,1,1],
                [0,1,1,1,0,1,1],
                [0,0,0,0,0,1,1],
                [0,0,0,0,0,1,1],
                [0,0,0,0,1,1,0],
                [0,0,0,1,1,0,0],
                [0,1,1,0,0,0,0]
            ],//9
            [
                [0,0,0,0],
                [0,0,0,0],
                [0,1,1,0],
                [0,1,1,0],
                [0,0,0,0],
                [0,0,0,0],
                [0,1,1,0],
                [0,1,1,0],
                [0,0,0,0],
                [0,0,0,0]
            ],//10
            [
	             [0,0,0,0],
	             [0,0,0,0],
	             [0,0,0,0],
	             [0,0,0,0],
	             [0,0,0,0],
	             [0,0,0,0],
	             [0,0,0,0],
	             [0,0,0,0],
	             [0,1,1,0],
	             [0,1,1,0]
	         ]//11:
        ];
    
    function reset(cxt) {
    	var nums = [];
    	context.fillStyle = "#005eac";
    	nums.push({num: 0});
    	nums.push({num: 0});
    	nums.push({num: 10});
    	nums.push({num: 0});
    	nums.push({num: 0});
    	nums.push({num: 11});
    	nums.push({num: 0});
    	
    	var offsetX = OFFSET_X,
    	offsetY = OFFSET_Y;
    	for (var x = 0; x < nums.length; x++) {
    		nums[x].offsetX = offsetX;
    		offsetX = drawSingleNumber(offsetX, offsetY, nums[x].num, cxt);
    		//两个数字连一块，应该间隔一些距离
    		if (x < nums.length - 1) {
    			if ((nums[x].num != 10) && (nums[x + 1].num != 10) && (nums[x].num != 11) && (nums[x + 1].num != 11)) {
    				offsetX += NUMBER_GAP;
    			}
    		}
    	}
    }
    function drawDatetime(cxt) {
        if (millionSecond >= 9) {
            millionSecond = 0;
            second++;
        }
        if (second > 59) {
            second = 0;
            minute++;
        }
        if (minute > 59) {
            minute = 0;
            hour++;
        }
        millionSecond++;

        var nums = [];
        context.fillStyle = "#005eac";
        if (hour > 0) {
            var hArr = ((hour < 10) ? "0" + hour: hour.toString()).split("");
            for (key in hArr) {
                nums.push({
                    num: hArr[key]
                });
            }
            nums.push({
                num: 10
            }); //冒号
        }
        var mArr = ((minute < 10) ? "0" + minute: minute.toString()).split("");
        var sArr = ((second < 10) ? "0" + second: second.toString()).split("");
        //	var msArr = ((millionSecond < 10) ? "0"+millionSecond : millionSecond.toString()).split("");
        var msArr = millionSecond.toString().split("");
        for (key in mArr) {
            nums.push({
                num: mArr[key]
            });
        }
        nums.push({
            num: 10
        }); //冒号
        for (key in sArr) {
            nums.push({
                num: sArr[key]
            });
        }
        nums.push({
            num: 11
        }); //点号
        for (key in msArr) {
            nums.push({
                num: msArr[key]
            });
        }

        var offsetX = OFFSET_X,
        offsetY = OFFSET_Y;
        for (var x = 0; x < nums.length; x++) {
            nums[x].offsetX = offsetX;
            offsetX = drawSingleNumber(offsetX, offsetY, nums[x].num, cxt);
            //两个数字连一块，应该间隔一些距离
            if (x < nums.length - 1) {
                if ((nums[x].num != 10) && (nums[x + 1].num != 10) && (nums[x].num != 11) && (nums[x + 1].num != 11)) {
                    offsetX += NUMBER_GAP;
                }
            }
        }
        //说明这是初始化
        if ((currentNums.length == 0) ) {
            currentNums = nums;
        } else {
            //进行比较
            for (var index = 0; index < nums.length-2; index++) {
                if (currentNums[index].num != nums[index].num) {
                    //不一样时，添加彩色小球
                    addBalls(nums[index]);
                    currentNums[index].num = nums[index].num;
                }
            }
        }
        renderBalls(cxt);
        updateBalls();
    }
    function addBalls(item) {
        var num = item.num;
        var numMatrix = digit[num];
        for (var y = 0; y < numMatrix.length; y++) {
            for (var x = 0; x < numMatrix[y].length; x++) {
                if (numMatrix[y][x] == 1) {
                    var ball = {
                        offsetX: item.offsetX + RADIUS + RADIUS * 2 * x,
                        offsetY: 30 + RADIUS + RADIUS * 2 * y,
                        color: colors[Math.floor(Math.random() * colors.length)],
                        g: 1.5 + Math.random(),
                        vx: Math.pow( - 1, Math.ceil(Math.random() * 10)) * 4 + Math.random(),
                        vy: -5
                    }
                    balls.push(ball);
                }
            }
        }
    }
    function renderBalls(cxt) {
        for (var index = 0; index < balls.length; index++) {
            cxt.beginPath();
            cxt.fillStyle = balls[index].color;
            cxt.arc(balls[index].offsetX, balls[index].offsetY, RADIUS, 0, 2 * Math.PI);
            cxt.fill();
        }
    }
    function updateBalls() {
        var i = 0;
        for (var index = 0; index < balls.length; index++) {
            var ball = balls[index];
            ball.offsetX += ball.vx;
            ball.offsetY += ball.vy;
            ball.vy += ball.g;
            if (ball.offsetY > (WINDOW_HEIGHT - RADIUS)) {
                ball.offsetY = WINDOW_HEIGHT - RADIUS;
                ball.vy = -ball.vy * u;
            }
            if (ball.offsetX > RADIUS && ball.offsetX < (WINDOW_WIDTH - RADIUS)) {
                balls[i] = balls[index];
                i++;
            }
        }
        //去除出边界的球
        for (; i < balls.length; i++) {
            balls.pop();
        }
    }
    function drawSingleNumber(offsetX, offsetY, num, cxt) {
        var numMatrix = digit[num];
        for (var y = 0; y < numMatrix.length; y++) {
            for (var x = 0; x < numMatrix[y].length; x++) {
                if (numMatrix[y][x] == 1) {
                    cxt.beginPath();
                    cxt.arc(offsetX + RADIUS + RADIUS * 2 * x, offsetY + RADIUS + RADIUS * 2 * y, RADIUS, 0, 2 * Math.PI);
                    cxt.fill();
                }
            }
        }
        cxt.beginPath();
        offsetX += numMatrix[0].length * RADIUS * 2;
        return offsetX;
    }
    
    var canvas = document.getElementById("canvas");
    canvas.width = WINDOW_WIDTH;
    canvas.height = WINDOW_HEIGHT;
    context = canvas.getContext("2d");

    // 页面自定义  START
    // 计次操作 START
    function isnertRow() {
    	var hStr = (hour < 10) ? "0" + hour: hour.toString();
    	var mStr = (minute < 10) ? "0" + minute: minute.toString();
    	var sArr = (second < 10) ? "0" + second: second.toString();
    	var msStr = (millionSecond < 10) ? "0"+millionSecond : millionSecond.toString();
    	
    	$("tbody").append("<tr><td>"+count+"</td><td><input id='rec_"+count+"' type='text' maxlength='32' class='span6 m-wrap' data-provide='typeahead' placeholder='请输入计次"+count+"'></td><td>"+hStr+":"+mStr+":"+sArr+"."+msStr+"</td></tr>");
    	$("#rec_"+count).autocomplete({
    		source: singleIds
    	});
    	$("#rec_"+count).click(function() {
    		$(this).select();
    	});
    }
    // 计次操作 END
    
    // 按钮时间监听 START
    $("#control").click(function() {
        if (!ctrlStatus || ctrlStatus == 'STOPED') {
        	//开始操作
            timer = setInterval(function() {
                //清空整个Canvas，重新绘制内容
                context.clearRect(0, 0, context.canvas.width, context.canvas.height);
                drawDatetime(context);
            }, 100);
            ctrlStatus = "RUNNING";
            recStatus = "Y";
            $("#control").text("暂停");
            $("#record").text("计次");
        } else {
        	//暂停操作
            clearInterval(timer);
            ctrlStatus = "STOPED";
            recStatus = "N";
            $("#control").text("开始");
            $("#record").text("重置");
        }
    });
    $("#record").click(function() {
        if (!recStatus || recStatus == 'N') {
        	//重置操作
        	hour = 0;
        	minute = 0;
        	second = 0;
        	millionSecond = 0;
        	count = 0;
            context.clearRect(0, 0, context.canvas.width, context.canvas.height);
            reset(context);
            $("tbody").empty();
        } else {
        	//计次操作
        	count++;
        	isnertRow();
        }
    });
  //保存活动
    $('#save').on('click',function(){
    	var submit = true;
    	layer.prompt({
    	    title: '请输入本次计时活动标题'
    	}, function(title){
    		var loader = layer.load(1);
    		if(!title || ""==title.trim()) {
    			layer.msg("活动名称不能为空");
    			layer.close(loader);
    			return;
    		}
    		var parmObj = {
    				title : title,
    				type : 1,
    				recordList : []
    		}
    		$("tbody tr").each(function(index){
    			var cnt = $(this).children().eq(1).children().first().val();
    			var rec = $(this).children().eq(2).text();
    			if(!cnt || !rec) {
    				submit = false;
    				return false;
    			}
    			parmObj.recordList[index] = {
    					content : $(this).children().eq(1).children().first().val(),
    					recordTime : $(this).children().eq(2).text()
    				}
    		});
    		if(!submit) {
    			layer.msg("计次名称不能为空");
    			layer.close(loader);
    			return;
    		}
    		if(!parmObj.recordList || parmObj.recordList.length==0) {
    			layer.msg("活动至少有一条计次记录");
    			layer.close(loader);
    			return;
    		}
    		$.ajax({
    		     type: 'POST',
    		     url: getRootPath()+"timer/stopwatch/save.do",
    		     data: JSON.stringify(parmObj),
    		     dataType:"json",  
    		     contentType : 'application/json;charset=utf-8', //设置请求头信息  
    	    	 success: function(data){
    	    		 layer.close(loader);
    	    		 layer.msg(data.msg);
    	    		 if(data.success) {
    	    			 window.location.href = getRootPath()+'center/timer/result.html?tid='+data.tid;
    	    		 }
    	    	 }
    		});
    	});
    });
    // 按钮时间监听 END
    // 页面自定义 END

    //初始画面
    context.clearRect(0, 0, context.canvas.width, context.canvas.height);
    reset(context);
    
});